package com.flute.haflute.agent.manage;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.flute.haflute.jobbox.common.CloudContext;

public class UnixJvmScript implements IjvmScript {

	private File workpath = new File(CloudContext.getRootDir());
	String xms = "-Xms128M";
	String xmx = "-Xmx2000M";
	String Objectpath;
	File classPath;

	UnixJvmScript(String mainClassName, File libPath) {
		this.setRunObject(mainClassName);
		this.classPath = libPath;
	}

	@Override
	public List<String> getCommandList(String[] jvmParams) {
		List<String> list = new ArrayList<String>();
		list.add("java");
		list.add("-cp");
		list.add(getClassPath());
		list.add("-Xbatch");
		list.add(xms);
		list.add(xmx);

		for (String param : jvmParams) {
			list.add(param);
		}

		list.add(Objectpath);

		return list;
	}

	public String getClassPath() {
		StringBuilder classpath = new StringBuilder(".:%CLASSPATH%:").append(
				classPath.getAbsolutePath()).append("/../classes:");
		File[] libs = classPath.listFiles();
		if (libs != null) {
			for (int i = 0; i < libs.length; i++) {
				String oneLib = libs[i].getName();
				if (libs[i].isFile()
						&& (oneLib.endsWith(".jar") || (oneLib.endsWith(".zip")))) {
					classpath.append(classPath.getAbsolutePath()).append("/")
							.append(oneLib).append(':');
				}
			}
		}
		return classpath.toString();
	}

	public void setJvmMemory(int mix, int max) {
		this.xms = "-Xms" + String.valueOf(mix) + "M";
		this.xmx = "-Xms" + String.valueOf(max) + "M";

	}

	public void setWorkpath(File workpath) {
		this.workpath = workpath;
	}

	public void setRunObject(String Objectpath) {
		this.Objectpath = Objectpath;

	}

	/*
	 * @see com.flute.haflute.management.IjvmScript#getWorkpath()
	 */
	@Override
	public File getWorkpath() {
		return workpath;
	}

}
